import 'package:safetymonitor/app/components/custom_app_bar.dart';
import 'package:safetymonitor/app/components/personnel_department_tree/personnel_department_tree_controller.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/data/entities/application/department_tree_entity.dart';
import 'package:safetymonitor/app/data/entities/application/department_user_entity.dart';

/// 人员部门树状选择
class PersonnelDepartmentTreePage extends StatelessWidget {
  PersonnelDepartmentTreePage({super.key});

  final controller = Get.put(PersonnelDepartmentTreeController());

  /// 部门下人员信息
  /// [userEntity] 人员数据
  /// [level] 所在层级
  Widget _getUserTreeView(DepartmentUserEntity userEntity, int level) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          constraints: BoxConstraints(
            minHeight: 55.w,
          ),
          padding: EdgeInsets.symmetric(vertical: 10.w),
          child: Row(
            children: [
              // 间距
              SizedBox(width: 20.w * level),
              // 占位
              SizedBox(width: 40.w),
              Expanded(
                child: Text(
                  userEntity.getShowName(),
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w400,
                    color: const Color(0xff333333).withOpacity(0.5),
                  ),
                ),
              ),
              // 分割线
              Container(
                margin: EdgeInsets.symmetric(horizontal: 10.w),
                height: 20.w,
                width: 1.w,
                color: const Color(0xffDDE6F0),
              ),
              SizedBox(
                width: 80.w,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SvgPicture.asset(
                      controller.userIsSelected(userEntity)
                          ? 'assets/svg/icon_selection_box.svg'
                          : 'assets/svg/icon_un_selection_box.svg',
                      width: 16.w,
                      height: 16.w,
                    ),
                    AppGaps.hGap8,
                    Text(
                      '选择',
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w400,
                        color: const Color(0xff5C6DFF),
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ).clickOnce(() {
          controller.selectPersonnel(userEntity);
          controller.isAll=  controller.userListAll.length == controller.selectedUserList.length;//TODO--这里有问题
          controller.update();
        }),
        Divider(
          height: 0.1.w,
          color: const Color(0xffECECEC),
        ),
      ],
    );
  }

  /// 部门数据每一项的显示
  /// [treeEntity] 当前节点数据
  /// [level] 所在层级
  Widget _getTreeView(DepartmentTreeEntity treeEntity, int level) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          constraints: BoxConstraints(
            minHeight: 55.w,
          ),
          padding: EdgeInsets.symmetric(vertical: 10.w),
          child: Row(
            children: [
              // 间距
              SizedBox(width: 20.w * level),
              SizedBox(
                width: 40.w,
                child: SvgPicture.asset(
                  treeEntity.isExpand!
                      ? 'assets/svg/icon_arrow_drop.svg'
                      : 'assets/svg/icon_arrow_right.svg',
                  width: 12.w,
                  height: 12.w,
                ),
              ),
              Expanded(
                child: Text(
                  treeEntity.name!,
                  style: TextStyle(
                    fontSize: 15.sp,
                    fontWeight: FontWeight.w500,
                    color: const Color(0xff333333),
                  ),
                ),
              ),
            ],
          ),
        ).clickOnce(() {
          // AppToast.show('$level');
          controller.clickOnNode(treeEntity, level);
        }),
        Divider(
          height: 0.1.w,
          color: const Color(0xffDDE6F0),
        ),
        // if (treeEntity.isExpand!)
        // AnimatedSize(
        //   duration: const Duration(milliseconds: 300),
        //   // curve: Curves.easeInExpo,
        //   curve: Curves.easeInOutExpo,
        //   child: _buildChildTree(treeEntity, level),
        // ),
        AnimatedSize(
          duration: const Duration(milliseconds: 500),
          // curve: Curves.easeInExpo,
          curve: Curves.easeInOutExpo,
          child: SizedBox(
            height: treeEntity.isExpand! ? null : 0,
            child: Column(
              children: [
                // 组织部门
                ...treeEntity.children!.map((item) {
                  return _getTreeView(item, level + 1);
                }),
                // 人员
                ...treeEntity.userList!.map((item) {
                  return _getUserTreeView(item, level + 1);
                })
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildChildTree(DepartmentTreeEntity treeEntity, int level) {
    if (treeEntity.children == null) return const SizedBox.shrink();
    // 延迟加载子节点
    return Column(
      children: [
        // 组织部门
        ...treeEntity.children!.map((item) {
          return _getTreeView(item, level + 1);
        }),
        // 人员
        ...treeEntity.userList!.map((item) {
          return _getUserTreeView(item, level + 1);
        })
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return  GetBuilder(
      init: controller,
      builder: (_) {
        return Scaffold(
          appBar: CustomAppBar(
            titleText: controller.title,
            actions: [
              Visibility(
                visible: !controller.isRadio,
                child: SizedBox(
                  width: 80.w,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SvgPicture.asset(
                       controller.isAll
                            ? 'assets/svg/icon_selection_box.svg'
                            : 'assets/svg/icon_un_selection_box.svg',
                        width: 16.w,
                        height: 16.w,
                      ),
                      AppGaps.hGap8,
                      Text(
                        '全选',
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w400,
                          color: const Color(0xff5C6DFF),
                        ),
                      )
                    ],
                  ),
                ).clickOnce(controller.isAllSelect),
              ),
            ],
          ),
          body:  Column(
            children: [
              Container(
                color: const Color(0xffF5F5F6),
                height: 10.w,
              ),
              controller.departmentTreeList.isNotEmpty
                  ? Expanded(
                child: ListView.builder(//如果树的数据量较大，可以将 SingleChildScrollView 换成 ListView.builder，它可以懒加载和回收滚动区域外的子节点，避免一次性加载整个树结构
                  //ListView.builder 的优势是它只渲染当前可见区域的节点，而不是一次性渲染整个列表，这样可以显著提高性能。
                  itemCount: controller.departmentTreeList.length,
                  itemBuilder: (context, index) {
                    return _getTreeView(controller.departmentTreeList[index], 0);
                  },
                ),

                // child: SingleChildScrollView(
                //           child: Column(
                //       children: controller.departmentTreeList.map((item) {
                //         return _getTreeView(item, 0);
                //       }).toList(),
                //     )),

              )
                  : Expanded(
                child: Container(
                  color: Colors.white,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      AppGaps.vGap36,
                      SvgPicture.asset('assets/svg/zhiban_empty_bg.svg'),
                      Text(
                        '暂无内容',
                        style: TextStyle(
                          color: const Color(0xFFC7CEE5),
                          fontSize: 14.sp,
                        ),
                      ),
                      AppGaps.vGap40,
                    ],
                  ),
                ),
              ),
              SizedBox(height: 70.w)
            ],
          ),
          bottomSheet: Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 5.w),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: const Color(0xffBCBCC5).withOpacity(0.3), // 阴影颜色
                  offset: const Offset(0, -5), // 阴影的偏移量，向上偏移，即上方阴影
                  blurRadius: 10.0, // 阴影的模糊半径
                  spreadRadius: 2.0, // 阴影的扩散半径
                ),
              ],
            ),
            child: Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppColors.blue_button,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(22.r),
                      ),
                    ),
                    onPressed: controller.complete,
                    child: Text(
                      '确定',
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.white,
                      ),
                    ),
                  ),
                )
              ],
            ),
          ),
        );
      },
    );
  }
}
